package com.dcjt.firehotcarpad.widget

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.animation.AccelerateInterpolator
import androidx.core.content.ContextCompat
import com.aries.library.fast.util.SizeUtil
import com.dcjt.firehotcarpad.R


/**
 * <p>文件描述：支持拖动的横向进度条<p>
 * <p>@author 烤鱼<p>
 * <p>@date 2020/2/25 0025 <p>
 * <p>@update 2020/2/25 0025<p>
 * <p>版本号：1<p>
 *
 */
class DragProgress @JvmOverloads constructor(
    context: Context,
    attributes: AttributeSet? = null,
    defStyleRes: Int = 0
) : View(context, attributes, defStyleRes) {
    //背景线段的画笔
    private val bgPaint: Paint = Paint()
    //进度线段的画笔
    private val progressPaint: Paint = Paint()
    //圆点指示器的画笔
    private val circlePaint: Paint = Paint()
    //圆点指示器的半径
    private var mCircleRadius =SizeUtil.dp2px(5f)
    //进度条的最大宽度
    private var maxProgress = 0

    //进度条当前的宽度
    private var currentProgress = 0f

    //当前View的宽度
    private var w = 0

    //当前View的高度
    private var h = 0

    //距离左边的内边距
    private var paddingL = 0

    //距离右边的内边距
    private var paddingR = 0

    // 进度条的比例默认为百分比
    var rate = 100

    var onProgressListener: ((progress: Float) -> Unit)? = null
    // 是否支持滑动
    var dragEnable = true

    init {
        bgPaint.color = Color.parseColor("#F0F0F0")
        //填充且描边
        bgPaint.style = Paint.Style.FILL_AND_STROKE
        //抗锯齿
        bgPaint.isAntiAlias = true
        //线冒的头是圆的
        bgPaint.strokeCap = Paint.Cap.ROUND
        // 线宽为 3dp
        bgPaint.strokeWidth = SizeUtil.dp2px(3f).toFloat()


        progressPaint.color = Color.parseColor("#06A7FF")
        progressPaint.style = Paint.Style.FILL_AND_STROKE
        progressPaint.isAntiAlias = true
        progressPaint.strokeCap = Paint.Cap.ROUND
        progressPaint.strokeWidth = SizeUtil.dp2px(3f).toFloat()


        circlePaint.isAntiAlias = true
        circlePaint.color = ContextCompat.getColor(context, R.color.mainColor)
        circlePaint.setShadowLayer(
            SizeUtil.dp2px(2f).toFloat(),
            0f,
            0f,
            Color.parseColor("#38000000")
        )
        circlePaint.style = Paint.Style.FILL
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val minHeight = mCircleRadius.toInt() * 2 + (SizeUtil.dp2px(2f) * 2).toInt()
        val height = resolveSize(minHeight, heightMeasureSpec)
        setMeasuredDimension(width, height)
    }



    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        w = width
        h = height

        //让左边距至少为半个圆点指示器的距离
        paddingL = paddingLeft
        if (paddingLeft < mCircleRadius) {
            paddingL = mCircleRadius.toInt()
        }
        //让右边距至少为半个圆点指示器的距离
        paddingR = paddingRight
        if (paddingRight < mCircleRadius) {
            paddingR = mCircleRadius.toInt()
        }

        //如果当前进度小于左边距
        setCurrentProgress()
        //最大进度长度等于View的宽度-(左边的内边距+右边的内边距)
        maxProgress = w - paddingL - paddingR
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        //从（左边距，View高度的一半）开始，到（View宽度-右边距，View高度的一半）还将绘制灰色背景线段
        canvas?.drawLine(paddingL.toFloat(), h / 2f, w.toFloat() - paddingR, h / 2f, bgPaint)
        //绘制实际进度线段
        //从（左边距，View高度的一半）开始，到（现在的触摸到的进度宽度，View高度的一半）还将绘制灰色背景线段
        canvas?.drawLine(
            paddingL.toFloat(),
            h / 2f,
            currentProgress.toFloat(),
            h / 2f,
            progressPaint
        )
        //要支持阴影下过必须关闭硬件加速
        setLayerType(LAYER_TYPE_SOFTWARE, null)//发光效果不支持硬件加速
        //绘制圆点
        canvas?.drawCircle(currentProgress.toFloat(), height / 2f,
            mCircleRadius.toFloat(), circlePaint)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if(dragEnable)return true
        event ?: return false
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                mCircleRadius = SizeUtil.dp2px(8f)
                circlePaint.color = Color.alpha(0x664287FF)
                //设置进度值
                setMotionProgress(event)
                return true
            }
            MotionEvent.ACTION_MOVE -> {
                //获取当前触摸点，赋值给当前进度
                setMotionProgress(event)
                return true
            }
            MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
                mCircleRadius = SizeUtil.dp2px(5f)
                circlePaint.color = ContextCompat.getColor(context, R.color.mainColor)
                return true
            }
            else -> return false
        }

    }

    private fun setCurrentProgress() {
        if (currentProgress < paddingL) {
            currentProgress = paddingL.toFloat()
        } else if (currentProgress > w - paddingR) {
            currentProgress = w - paddingR.toFloat()
        }
    }

    private fun setMotionProgress(event: MotionEvent) {
        //获取当前触摸点，赋值给当前进度
        currentProgress = event.x
        //如果当前进度小于左边距
        setCurrentProgress()
        //看数学公式就可以了,实际百分比进度数值
        val result =
            (currentProgress - paddingL) * rate / maxProgress.toFloat()
        //进行空值判断
        onProgressListener?.invoke(result)
        invalidate()
    }

    //设置当前进度条进度,从1到100
    fun setProgress(progress: Int) {
        var value = progress
        if(progress > rate)value = rate
        if(progress < 0 ) value = 0

        setCurrentProgress()
        //设置当前进度的宽度
        val progress = progress * maxProgress.toFloat() / rate + paddingL
        onProgressListener?.invoke(progress)

        val animator = ValueAnimator.ofFloat(currentProgress, progress)
        animator.duration = 1000
        animator.interpolator = AccelerateInterpolator()
        animator.addUpdateListener {
            currentProgress = it.animatedValue as Float
            invalidate()
        }
        animator.start()
    }

}